package com.business.commons.baseUtil;

import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

/**
 * 
 * @author Lanbo
 *
 */
public class HashHmacUtil {
	
	

	private static HashHmacUtil instance;
	
	public static HashHmacUtil get() {
		if(instance == null ){
			instance = new HashHmacUtil(); 
		}
		return instance;
	}
	
	
	/**
	 * hmac_sha1 加密算法
	 * @param value 要加密的字符串
	 * @param key  加密私钥
	 * @return
	 */
    public  String hmac_sha1(String value, String key) {  
        try {  
            // Get an hmac_sha1 key from the raw key bytes  
            byte[] keyBytes = key.getBytes();             
            SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA1");  
  
            // Get an hmac_sha1 Mac instance and initialize with the signing key  
            Mac mac = Mac.getInstance("HmacSHA1");  
            mac.init(signingKey);  
  
            // Compute the hmac on input data bytes  
            byte[] rawHmac = mac.doFinal(value.getBytes());  
  
            // Convert raw bytes to Hex  
            String hexBytes = byte2hex(rawHmac);  
            return hexBytes;  
        } catch (Exception e) {  
            throw new RuntimeException(e);  
        }  
    }  
  
    private  String byte2hex(final byte[] b){  
        String hs="";  
        String stmp="";  
        for (int n=0; n<b.length; n++){  
            stmp=(java.lang.Integer.toHexString(b[n] & 0xFF));  
            if (stmp.length()==1) hs=hs+"0"+stmp;  
                else hs=hs+stmp;  
        }  
        return hs;  
    }  
    /**
     * 返回Base64编码后的字符串
     * @param 要加密的字符串
     * @param 私钥
     * @return
     * @throws GeneralSecurityException
     * @throws UnsupportedEncodingException
     */
    public  String computeSignature(String baseString, String keyString)  throws GeneralSecurityException, UnsupportedEncodingException {

    	    SecretKey secretKey = null;

    	    byte[] keyBytes = keyString.getBytes();
    	    secretKey = new SecretKeySpec(keyBytes, "HmacSHA1");

    	    Mac mac = Mac.getInstance("HmacSHA1");

    	    mac.init(secretKey);

    	    byte[] text = baseString.getBytes();

    	    return new String(Base64Util.encode(mac.doFinal(text))).trim();
    	    
    	  }
}
